﻿import { AbpSessionService } from '@abp/session/abp-session.service';
import { Component, Injector, OnInit, AfterViewInit } from '@angular/core';
import { Router } from '@angular/router';
import { accountModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import {
    SessionServiceProxy,
    UpdateUserSignInTokenOutput,
    TokenAuthServiceProxy
} from '@shared/service-proxies/stock-service-proxies';
import { UrlHelper } from 'shared/helpers/UrlHelper';
import { ExternalLoginProvider, LoginService } from './login.service';
import { ImpersonationService } from '@app/admin/users/impersonation.service';
import { AppConsts } from '@shared/AppConsts';

@Component({
    templateUrl: './login.component.html',
    animations: [accountModuleAnimation()]
})
export class LoginComponent extends AppComponentBase implements OnInit {
    submitting = false;
    isMultiTenancyEnabled: boolean = this.multiTenancy.isEnabled;

    ssoUrl = AppConsts.ssoUrl + '/Home/Index';

    domainUsername: string;

    constructor(
        injector: Injector,
        public loginService: LoginService,
        private _router: Router,
        private _sessionService: AbpSessionService,
        private _sessionAppService: SessionServiceProxy,
        public _impersonationService: ImpersonationService,
        private _tokenAuthService: TokenAuthServiceProxy
    ) {
        super(injector);
    }

    get multiTenancySideIsTeanant(): boolean {
        return this._sessionService.tenantId > 0;
    }

    get isTenantSelfRegistrationAllowed(): boolean {
        return this.setting.getBoolean('App.TenantManagement.AllowSelfRegistration');
    }

    get isSelfRegistrationAllowed(): boolean {
        if (!this._sessionService.tenantId) {
            return false;
        }

        return this.setting.getBoolean('App.UserManagement.AllowSelfRegistration');
    }

    ngOnInit(): void {
        if (this._sessionService.userId > 0 && UrlHelper.getReturnUrl() && UrlHelper.getSingleSignIn()) {
            this._sessionAppService.updateUserSignInToken().subscribe((result: UpdateUserSignInTokenOutput) => {
                const initialReturnUrl = UrlHelper.getReturnUrl();
                const returnUrl =
                    initialReturnUrl +
                    (initialReturnUrl.indexOf('?') >= 0 ? '&' : '?') +
                    'accessToken=' +
                    result.signInToken +
                    '&userId=' +
                    result.encodedUserId +
                    '&tenantId=' +
                    result.encodedTenantId;

                location.href = returnUrl;
            });
        }

        let state = UrlHelper.getQueryParametersUsingHash().state;
        if (state && state.indexOf('openIdConnect') >= 0) {
            this.loginService.openIdConnectLoginCallback({});
        }

        let self = this;
        let iframe = document.createElement('iframe');
        iframe.style.display = 'none';
        var flag = 0;

        iframe.onload = function() {
            if (flag === 1) {
                self.domainUsername = iframe.contentWindow.name;
                iframe.contentWindow.close();
            } else if (flag === 0) {
                flag = 1;
                iframe.contentWindow.location.href = AppConsts.appBaseUrl + '/assets/common/htmls/proxy.html';
            }
        };

        iframe.src = this.ssoUrl;

        document.body.appendChild(iframe);
    }

    login(): void {
        abp.ui.setBusy(undefined, '', 1);
        this.submitting = true;
        this.loginService.authenticate(() => {
            this.submitting = false;
            abp.ui.clearBusy();
        });
    }

    domainLogin(): void {
        abp.ui.setBusy(undefined, '', 1);
        this.submitting = true;
        this.loginService.authenticateDomin(this.domainUsername, () => {
            this.submitting = false;
            abp.ui.clearBusy();
        });
    }

    externalLogin(provider: ExternalLoginProvider) {
        this.loginService.externalAuthenticate(provider);
    }
}
